package com.mhfelipe.applet.print;

import org.apache.commons.io.IOUtils;

import java.applet.Applet;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

public  class AbstractPrint extends Applet {

    public final String getContent() {

        String codElist = clean(getParameter("codElist"));
        String email = clean(getParameter("email"));
        String cidade = clean(getParameter("cidade"));
        String residencial = clean(getParameter("residencial"));
        String celular = clean(getParameter("celular"));
        String endereco = clean(getParameter("endereco"));
        String numero = clean(getParameter("numero"));
        String nome = clean(getParameter("nome"));

        String stringFile = readFile();

        stringFile = stringFile.replaceFirst("\\{\\$codElist\\}", codElist);
        stringFile = stringFile.replaceFirst("\\{\\$email\\}", email);
        stringFile = stringFile.replaceFirst("\\{\\$cidade\\}", cidade);
        stringFile = stringFile.replaceFirst("\\{\\$residencial\\}", residencial);
        stringFile = stringFile.replaceFirst("\\{\\$celular\\}", celular);
        stringFile = stringFile.replaceFirst("\\{\\$endereco\\}", endereco);
        stringFile = stringFile.replaceFirst("\\{\\$numero\\}", numero);
        stringFile = stringFile.replaceFirst("\\$nome", nome);

        return stringFile;
    }

    private String readFile() {
        try {
            InputStream inputStream = getClass().getResourceAsStream("/content.txt");
            StringWriter writer = new StringWriter();
            IOUtils.copy(inputStream, writer, "utf-8");
            return writer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    private String clean(String str) {
        if (str == null) {
            return "";
        }
        return str;
    }

}
